'use strict';
import React, { useState, useEffect, useRef } from 'react';
import { Table, Space, Button, Form, Input } from 'antd';
import Gconfirm from '@/component/confirm'
import {
  PlusOutlined,
} from '@ant-design/icons';
import { layout } from '../conf'
import Gmodal from '@/component/modal'
import styles from './index.less';

/*
* 组件注释
* create by wuqiong
* creation time 2022/04/25
* 拓展属性
* */

const Index = (props) => {
  const { id, type, prefix, width } = props;
  const [elementPropertyList, setElementPropertyList] = useState([]);
  const [propertyForm, setPropertyForm] = useState({});
  const [editingPropertyIndex, setEditingPropertyIndex] = useState(-1);
  const [propertyFormModelVisible, setPropertyFormModelVisible] = useState(false);

  const [form] = Form.useForm();
  const dataRef = useRef({})

  const resetAttributesList = () => {
    dataRef.current.bpmnElement = window.bpmnInstances.bpmnElement;
    dataRef.current.otherExtensionList = []; // 其他扩展配置
    dataRef.current.bpmnElementProperties =
      dataRef.current.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
        if (ex.$type !== `${prefix}:Properties`) {
          dataRef.current.otherExtensionList.push(ex);
        }
        return ex.$type === `${prefix}:Properties`;
      }) ?? [];

    // 保存所有的 扩展属性字段
    dataRef.current.bpmnElementPropertyList = dataRef.current.bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), []);
    // 复制 显示
    const elementPropertyList = JSON.parse(JSON.stringify(dataRef.current.bpmnElementPropertyList ?? []));
    setElementPropertyList(elementPropertyList)
  }
  const openAttributesForm = (attr, index) => {

    const propertyForm = index === -1 ? {} : JSON.parse(JSON.stringify(attr));
    setEditingPropertyIndex(index)
    setPropertyForm(propertyForm)
    setPropertyFormModelVisible(true)
    setTimeout(() => form.resetFields(), 0);
  }
  const removeAttributes = (index) => {
    elementPropertyList.splice(index, 1);
    setElementPropertyList([...elementPropertyList])
    dataRef.current.bpmnElementPropertyList.splice(index, 1);
    // 新建一个属性字段的保存列表
    const propertiesObject = window.bpmnInstances.moddle.create(`${prefix}:Properties`, {
      values: dataRef.current.bpmnElementPropertyList
    });
    updateElementExtensions(propertiesObject);
    resetAttributesList();
  }
  const saveAttribute = () => {
    const { name, value } = form.getFieldsValue();
    if (editingPropertyIndex !== -1) {
      window.bpmnInstances.modeling.updateModdleProperties(dataRef.current.bpmnElement, dataRef.current.bpmnElementPropertyList[editingPropertyIndex], {
        name,
        value
      });
    } else {
      // 新建属性字段
      const newPropertyObject = window.bpmnInstances.moddle.create(`${prefix}:Property`, { name, value });
      // 新建一个属性字段的保存列表
      const propertiesObject = window.bpmnInstances.moddle.create(`${prefix}:Properties`, {
        values: dataRef.current.bpmnElementPropertyList.concat([newPropertyObject])
      });
      updateElementExtensions(propertiesObject);
    }
    setPropertyFormModelVisible(false)
    resetAttributesList();
  }
  const updateElementExtensions = (properties) => {
    const extensions = window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
      values: dataRef.current.otherExtensionList.concat([properties])
    });
    window.bpmnInstances.modeling.updateProperties(dataRef.current.bpmnElement, {
      extensionElements: extensions
    });
  }

  useEffect(() => {
    id && id.length && resetAttributesList();
  }, [id])

  const columns = [
    {
      title: "序号",
      width: "50px",
      render: (_, __, index) => index + 1,
    },
    {
      title: "属性名",
      dataIndex: "name",
      key: "name",
      ellipsis: true,
    },
    {
      title: "属性值",
      dataIndex: "value",
      key: "value",
      ellipsis: true,
    },
    {
      title: "操作",
      width: 80,
      key: "operation",
      render: (_, record, idx) => {
        return <Space >
          <Button onClick={() => openAttributesForm(record, idx)} type="link" style={{ padding: 0, fontSize: "12px", height: "18px" }}>编辑</Button>
          <Gconfirm
            content={"确认移除该属性吗？"}
            onConfirm={() => removeAttributes(idx)}>
            <Button type="link" danger style={{ padding: 0, fontSize: "12px", height: "18px" }}>移除</Button>
          </Gconfirm>
        </Space >
      }
    },
  ]
  return <div className={styles.properties}>
    <Table
      size='small' bordered rowKey={"event"}
      className="bpmn_table"
      columns={columns}
      pagination={false}
      dataSource={elementPropertyList} />
    <Button onClick={() => openAttributesForm(null, -1)} type="primary" className={styles.add_btn} icon={<PlusOutlined />} >添加监听器</Button>
    <Gmodal
      title={'属性配置'} width={500}
      bodyStyle={{
        minHeight: "auto",
        paddingBottom: 0
      }}
      visible={propertyFormModelVisible}
      handleOk={() => saveAttribute()}
      handleCancel={() => setPropertyFormModelVisible(false)} >
      <Form {...layout} initialValues={propertyForm} preserve={false} form={form} name="propertyForm" >
        <Form.Item name="name" label="属性名" >
          <Input allowClear />
        </Form.Item>
        <Form.Item name="value" label="属性值" >
          <Input allowClear />
        </Form.Item>
      </Form>
    </Gmodal>
  </div>
};
export default Index;